#include "boxwidget.h"
#include <QProcess>
#include "sysconf.h"
#include <QMessageBox>
#include <QFile>
#include "sysconf.h"
#include "ftputil.h"

extern bool updateBoxInfo();
extern BoxInfo boxInfo;
extern FtpUtil ftp;
extern QByteArray rcstxt;
extern QByteArray profiletxt;


BoxWidget::BoxWidget(QWidget *parent) :
    QWidget(parent)
{
    setupUi(this);

    remotePath=currentPath="/home";
    localCurrentPath="/dist";

    remoteView->setColumnWidth(0,160);
    //remoteView->setColumnWidth(1,50);

    localModel = new FileSystemModel ;
    localView->setModel(localModel);
    localView->setColumnHidden(1,true);
    localView->setColumnHidden(2,true);
    localView->setColumnHidden(3,false);
    localView->setRootIndex(localModel->index("./dist"));
    localView->setColumnWidth(0,160);

    lineEdit->setText(boxInfo.dfip);
//    ethText1->setText(boxInfo.ip1);
//    ethText2->setText(boxInfo.ip2);

    rcs=new Rcs();
    profile=new Profile();

    connect(ipBtn,SIGNAL(clicked()),this,SLOT(reConnFtp()));
    connect(ethSetBtn,SIGNAL(clicked()),this,SLOT(setEth()));
    connect(remoteView, SIGNAL(itemActivated(QTreeWidgetItem*,int)),this, SLOT(processItem(QTreeWidgetItem*,int)));
    connect(remoteView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(showRemoteMenu(QPoint)));
    connect(localView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(showLocalMenu(QPoint)));
    connect(chbxAutorun,SIGNAL(clicked()),this,SLOT(autoRun()));
    connect(chbxTelnet,SIGNAL(clicked()),this,SLOT(setTelnet()));
    //connect(cancelBtn,SIGNAL(clicked()),this,SLOT(cancelAutoRun()));
    connect(&ftp,SIGNAL(clearRemoteView()),this,SLOT(clearRemote()));
    connect(&ftp,SIGNAL(addToRemote(QUrlInfo)),this,SLOT(addToList(QUrlInfo)));
    connect(&ftp,SIGNAL(setBoxInfo()),this,SLOT(loadBoxInfo()));

    initUi();


}


void BoxWidget::openOne()
{
//    QString path=QDir::currentPath();//获取程序当前目录
//    path.replace("/","\\");//将地址中的"/"替换为"\"，因为在Windows下使用的是"\"
//    path.append("\\dist\\onepower");
//    QProcess::startDetached("explorer "+path);//打开上面获取的目录
}

void BoxWidget::openMms()
{
//    QString path=QDir::currentPath();//获取程序当前目录
//    path.replace("/","\\");//将地址中的"/"替换为"\"，因为在Windows下使用的是"\"
//    path.append("\\dist\\mmslite");
//    QProcess::startDetached("explorer "+path);//打开上面获取的目录
}



bool BoxWidget::closeFtp()
{
    ftp.closeFtp();
}

void BoxWidget::initUi()
{
    ftp.cd(remotePath);
    ftp.list();
}


void BoxWidget::setTelnet()
{
    if(chbxTelnet->checkState()==Qt::Checked)
    {
        boxInfo.isTelnet=true;
    }
    else
    {
        boxInfo.isTelnet=false;
    }
    setEth();
}

void BoxWidget::setEth()
{
    const QString filename="/etc/init.d/rcS";
    boxInfo.ip1=ethip1->text().trimmed();
    boxInfo.netmask1=netmask1->text().trimmed();

    boxInfo.ip2=ethip2->text().trimmed();
    boxInfo.netmask2=netmask2->text().trimmed();



    if(!ftp.isconnect())
    {
        QMessageBox::information(this,"提示","正在连接ftp服务器或ftp连接失败");
        return;
    }

    ftp.upload(rcs->stdRcs().toAscii(),filename);

    QMessageBox::information(this,"提示","设置成功,需重启盒子后生效");

}
void BoxWidget::autoRun()
{
    if(chbxAutorun->checkState()==Qt::Checked)
    {
        setAutoRun();
    }
    else
    {
        cancelAutoRun();
    }
}

void BoxWidget::setAutoRun()
{
    const QString filename="/etc/profile";
    if(!ftp.isconnect())
    {
        QMessageBox::information(this,"提示","正在连接ftp服务器或ftp连接失败");
        return;
    }
    profile->isQt=true;
    profile->isAutoRun=true;
    ftp.upload(profile->stdProfile().toAscii(),filename);

    QMessageBox::information(this,"提示","程序自启动设置成功,重启后生效");

}

void BoxWidget::cancelAutoRun()
{
    if(!ftp.isconnect())
    {
        QMessageBox::information(this,"提示","正在连接ftp服务器或ftp连接失败");
        return;
    }
    profile->isQt=true;
    profile->isAutoRun=false;
    ftp.upload(profile->stdProfile().toAscii(),"/etc/profile");

    QMessageBox::information(this,"提示","程序取消自启动设置成功,重启后生效");
}

bool BoxWidget::reConnFtp()
{
    ftp.ftpip=lineEdit->text().trimmed();
    //if(ftp.isconnect())
    //{
       ftp.closeFtp();
   // }
    qDebug("connect ftp;");
    ftp.connectFtp();
    initUi();
}




void BoxWidget::addToList(const QUrlInfo &info)
{
     QTreeWidgetItem *item = new QTreeWidgetItem;
     item->setText(0, tr(info.name().toLatin1()));
     //item->setText(1, QString::number(info.size()).toLatin1());
     item->setText(1, info.lastModified().toString("yyyy-MM-dd HH:mm:ss").toLatin1());

     QPixmap pixmap(info.isDir() ? "./ico/dir.png" : "./ico/file.png");
     item->setIcon(0, pixmap);

     isDirectory[info.name()] = info.isDir();
     if(info.isDir())
     {
         currentDirectory.insert(currentPath+"/"+info.name());
     }
     remoteView->addTopLevelItem(item);
     if (!remoteView->currentItem())
     {
         remoteView->setCurrentItem(remoteView->topLevelItem(0));
         remoteView->setEnabled(true);
     }
}


void BoxWidget::processItem(QTreeWidgetItem *item, int /*column*/)
{
//    QString name = item->text(0);
//    if (isDirectory.value(name))
//    {
//        currentPath += "/";
//        currentPath += name;
//        ftp.cd(name);
//        ftp.list();
//        return;
//    }
}

void BoxWidget::cdToParent()
{

    currentPath = currentPath.left(currentPath.lastIndexOf('/'));
    if (currentPath.isEmpty())
    {
        ftp.cd("/home");
    }
    else
    {
        ftp.cd(currentPath);
    }
    ftp.list();
}


  void BoxWidget::showRemoteMenu(const QPoint &pos)
  {
      if(remoteMenu)
      {
          //delete remoteMenu;
          remoteMenu=NULL;
      }
      remoteMenu=new QMenu(remoteView);
      if(currentPath!="/home")
      {
            QAction *toParent=remoteMenu->addAction("上一级\t");
            connect(toParent,SIGNAL(triggered()),this,SLOT(cdToParent()));

      }
      QAction *refreshAction=remoteMenu->addAction("刷新\t");
      connect(refreshAction,SIGNAL(triggered()),this,SLOT(refreshRemote()));
      QAction *delAction=remoteMenu->addAction("删除\t");
      connect(delAction,SIGNAL(triggered()),this,SLOT(delRemote()));
      remoteMenu->exec(QCursor::pos());
  }


  void BoxWidget::showLocalMenu(const QPoint &pos)
  {
      if(localMenu)
      {
          //delete localMenu;
          localMenu=NULL;
      }
      localMenu=new QMenu(localView);
      QAction *upload=localMenu->addAction("上传\t");
      connect(upload,SIGNAL(triggered()),this,SLOT(upload()));
      QAction *refreshAction=localMenu->addAction("刷新\t");
      connect(refreshAction,SIGNAL(triggered()),this,SLOT(refreshLocal()));

      localMenu->exec(QCursor::pos());
  }

  void BoxWidget::upload()
  {
      if(!ftp.isconnect())
      {
          QMessageBox::information(this,"提示","正在连接ftp服务器或ftp连接失败");
          return;
      }

      emit openLogDlg();
      emit operlog("开始上传文件");


      //得到所有目录
      dirSet.clear();
      foreach (const QPersistentModelIndex &index, localModel->checkedIndexes)
      {
          QString path=QDir::currentPath();//获取程序当前目录
          path.append(localCurrentPath);
          QString filePath=localModel->filePath(index);
          QString temp=filePath.right(filePath.length()-path.length()-1);
          QFileInfo info(filePath);
          if(info.isDir())
          {
              if(!dirSet.contains(temp))
              {
                  dirSet.insert(temp);
              }
          }
      }

      int maxLen=0;
      foreach (const QString &value, dirSet)
      {
          if(value.length()>maxLen)
          {
              maxLen=value.length();
          }
      }
      QStringList strList;
      for(int i=0;i<=maxLen;i++)
      {
          foreach (const QString &value, dirSet)
          {
              if(value.length()==i)
              {
                  strList<<value;
              }
          }
      }
      if(strList.size()!=0)
      {

          if(!isDirectory.contains(strList.at(0)))
          {
              for(int j=0;j<strList.size();j++)
              {
                  ftp.mkdir(strList.at(j));
              }


          }
      }
      foreach (const QPersistentModelIndex &index, localModel->checkedIndexes)
      {
          QString path=QDir::currentPath();//获取程序当前目录
          path.append(localCurrentPath);
          QString filePath=localModel->filePath(index);
          QString temp=filePath.right(filePath.length()-path.length());
          QFileInfo info(filePath);
          FileBean bean;
          bean.filename=filePath;
          bean.remotePath=remotePath+temp;

          if(info.isFile())
          {

              ftp.upload(bean);
          }
      }
      this->refreshRemote();
     // emit operlog("上传文件完成");
  }


  void BoxWidget::refreshLocal()
  {
        localModel->refresh();
  }

  void BoxWidget::clearRemote()
  {
      remoteView->clear();
      isDirectory.clear();
  }

  void BoxWidget::delRemote()
  {
        QList<QTreeWidgetItem *> list=remoteView->selectedItems();
        for(int i=0;i<list.size();i++)
        {
            if(isDirectory[list.at(0)->text(0)])
            {
                ftp.rmdir(currentPath+"/"+list.at(0)->text(0));
            }
            else
            {
                ftp.rm(currentPath+"/"+list.at(0)->text(0));
            }

        }
        refreshRemote();
  }

   void BoxWidget::refreshRemote()
   {
       clearRemote();
       ftp.list();
   }


   void BoxWidget::loadBoxInfo()
   {
         QString rcsstr(rcstxt);
         if(rcsstr.contains("#telnet")||rcsstr.contains("telnet"))
         {
             boxInfo.isTelnet=true;
             chbxTelnet->setCheckState(Qt::Checked);
         }
         else
         {
             boxInfo.isTelnet=false;
             chbxTelnet->setCheckState(Qt::Unchecked);
         }
         int index=rcsstr.indexOf(QRegExp("eth0 [1-9]"));
         int index1=rcsstr.indexOf(QRegExp("eth0 down"));
         QString eth0str=rcsstr.mid(index,index1-index);

         QRegExp reg("[\\s]{1,}");
         QStringList eth0list=eth0str.split(reg);
         boxInfo.ip2=eth0list.at(1);
         boxInfo.netmask2=eth0list.at(3);

         int index2=rcsstr.indexOf(QRegExp("eth1 [1-9]"));
         int index3=rcsstr.indexOf(QRegExp("eth1 up"));
         QString eth1str=rcsstr.mid(index2,index3-index2);


         QStringList eth1list=eth1str.split(reg);
         boxInfo.ip1=eth1list.at(1);
         boxInfo.netmask1=eth1list.at(3);


         ethip1->setText(boxInfo.ip1);
         netmask1->setText(boxInfo.netmask1);
         ethip2->setText(boxInfo.ip2);
         netmask2->setText(boxInfo.netmask2);

         QString profilestr(profiletxt);
         if(profilestr.contains("#autorun"))
         {
             boxInfo.isAutoRun=true;
             chbxAutorun->setCheckState(Qt::Checked);
         }
         else
         {
             boxInfo.isAutoRun=false;
             chbxAutorun->setCheckState(Qt::Unchecked);
         }

   }







